package org.dromara.yuanshidian.service.impl;

import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.yuanshidian.domain.Ab02;
import org.dromara.yuanshidian.domain.Ab04Refund;
import org.dromara.yuanshidian.domain.bo.Ab04ExcelDTO;
import org.dromara.yuanshidian.domain.vo.ExportAb04Vo;
import org.dromara.yuanshidian.mapper.Ab02Mapper;
import org.dromara.yuanshidian.mapper.Ab04RefundMapper;
import org.springframework.stereotype.Service;
import org.dromara.yuanshidian.domain.bo.Ab04Bo;
import org.dromara.yuanshidian.domain.vo.Ab04Vo;
import org.dromara.yuanshidian.domain.Ab04;
import org.dromara.yuanshidian.mapper.Ab04Mapper;
import org.dromara.yuanshidian.service.IAb04Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 原人员账户明细(缴费明细)Service业务层处理
 *
 * @author TzhongTop
 * @date 2025-01-24
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class Ab04ServiceImpl implements IAb04Service {

    private final Ab04Mapper baseMapper;

    @Resource
    private Validator validator;

    @Resource
    private Ab02Mapper ab02Mapper;

    @Resource
    private Ab04RefundMapper ab04RefundMapper;

    //缴费期间
    String[] jrYear = {"1998","1999","2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"};
    //当年记账利率
    String[] jrMonthRate = {"0.0378","0.0378","0.0226","0.0198","0.0198","0.0198","0.0226","0.0226","0.028","0.0414","0.0226","0.0226","0.0275","0.035","0.0325","0.03","0.0275"};


    /**
     * 查询原人员账户明细(缴费明细)
     *
     * @param id 主键
     * @return 原人员账户明细(缴费明细)
     */
    @Override
    public Ab04Vo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询原人员账户明细(缴费明细)列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 原人员账户明细(缴费明细)分页列表
     */
    @Override
    public TableDataInfo<Ab04Vo> queryPageList(Ab04Bo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Ab04> lqw = buildQueryWrapper(bo);
        lqw.orderByAsc(Ab04::getGrmx02);
        lqw.eq(Ab04::getDelStatus, 0);
        Page<Ab04Vo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }
    /**
     * 查询符合条件的原人员账户明细(缴费明细)列表
     *
     * @param bo 查询条件
     * @return 原人员账户明细(缴费明细)列表
     */
    @Override
    public List<Ab04Vo> queryList(Ab04Bo bo) {
        LambdaQueryWrapper<Ab04> lqw = buildQueryWrapper(bo);
        lqw.eq(Ab04::getDelStatus, 0);
        lqw.orderByDesc(Ab04::getGrmx02);
        return baseMapper.selectVoList(lqw);
    }


    private LambdaQueryWrapper<Ab04> buildQueryWrapper(Ab04Bo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Ab04> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAaa027()), Ab04::getAaa027, bo.getAaa027());
        lqw.eq(StringUtils.isNotBlank(bo.getDw01()), Ab04::getDw01, bo.getDw01());
        lqw.like(StringUtils.isNotBlank(bo.getDw02()), Ab04::getDw02, bo.getDw02());
        lqw.eq(StringUtils.isNotBlank(bo.getGr03()), Ab04::getGr03, bo.getGr03());
        lqw.like(StringUtils.isNotBlank(bo.getGr04()), Ab04::getGr04, bo.getGr04());
        lqw.eq(StringUtils.isNotBlank(bo.getGr02()), Ab04::getGr02, bo.getGr02());
        lqw.eq(StringUtils.isNotBlank(bo.getGrmx01()), Ab04::getGrmx01, bo.getGrmx01());
        lqw.eq(StringUtils.isNotBlank(bo.getGrmx02()), Ab04::getGrmx02, bo.getGrmx02());
        lqw.eq(bo.getGrmx03() != null, Ab04::getGrmx03, bo.getGrmx03());
        lqw.eq(bo.getGr18() != null, Ab04::getGr18, bo.getGr18());
        lqw.eq(bo.getGr19() != null, Ab04::getGr19, bo.getGr19());
        lqw.eq(bo.getGr20() != null, Ab04::getGr20, bo.getGr20());
        lqw.eq(bo.getGrmx04() != null, Ab04::getGrmx04, bo.getGrmx04());
        lqw.eq(bo.getGrmx05() != null, Ab04::getGrmx05, bo.getGrmx05());
        lqw.eq(StringUtils.isNotBlank(bo.getGrmx06()), Ab04::getGrmx06, bo.getGrmx06());
        lqw.eq(bo.getDw14() != null, Ab04::getDw14, bo.getDw14());
        lqw.eq(bo.getCs03() != null, Ab04::getCs03, bo.getCs03());
        lqw.eq(StringUtils.isNotBlank(bo.getDw68()), Ab04::getDw68, bo.getDw68());
        lqw.eq(StringUtils.isNotBlank(bo.getDw24()), Ab04::getDw24, bo.getDw24());
        lqw.eq(bo.getSystime() != null, Ab04::getSystime, bo.getSystime());
        lqw.eq(StringUtils.isNotBlank(bo.getGrjx01()), Ab04::getGrjx01, bo.getGrjx01());
        lqw.eq(StringUtils.isNotBlank(bo.getTz01()), Ab04::getTz01, bo.getTz01());
        lqw.eq(StringUtils.isNotBlank(bo.getDh()), Ab04::getDh, bo.getDh());
        lqw.eq(StringUtils.isNotBlank(bo.getDw91()), Ab04::getDw91, bo.getDw91());
        lqw.eq(bo.getAaz223() != null, Ab04::getAaz223, bo.getAaz223());
        lqw.eq(bo.getStatus() != null, Ab04::getStatus, bo.getStatus());
        lqw.eq(bo.getDataFlag() != null, Ab04::getDataFlag, bo.getDataFlag());
        lqw.eq(bo.getDelStatus() != null, Ab04::getDelStatus, bo.getDelStatus());
        lqw.eq(bo.getJfStarttime() != null, Ab04::getJfStarttime, bo.getJfStarttime());
        lqw.eq(bo.getJfEndtime() != null, Ab04::getJfEndtime, bo.getJfEndtime());
        lqw.eq(StringUtils.isNotBlank(bo.getFileurl()), Ab04::getFileurl, bo.getFileurl());
        lqw.eq(StringUtils.isNotBlank(bo.getGr01()), Ab04::getGr01, bo.getGr01());
        lqw.eq(bo.getJsStartmonth() != null, Ab04::getJsStartmonth, bo.getJsStartmonth());
        lqw.eq(bo.getJsEndmonth() != null, Ab04::getJsEndmonth, bo.getJsEndmonth());
        lqw.eq(bo.getJfPaymentmonths() != null, Ab04::getJfPaymentmonths, bo.getJfPaymentmonths());
        lqw.eq(bo.getGrjfbx() != null, Ab04::getGrjfbx, bo.getGrjfbx());
        lqw.eq(bo.getGrzhbx() != null, Ab04::getGrzhbx, bo.getGrzhbx());
        lqw.eq(bo.getRefStatus() != null, Ab04::getRefStatus, bo.getRefStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getJfssfbz()), Ab04::getJfssfbz, bo.getJfssfbz());
        return lqw;
    }

    /**
     * 新增原人员账户明细(缴费明细)
     *
     * @param bo 原人员账户明细(缴费明细)
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(Ab04Bo bo) {
        Ab04 add = MapstructUtils.convert(bo, Ab04.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改原人员账户明细(缴费明细)
     *
     * @param bo 原人员账户明细(缴费明细)
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(Ab04Bo bo) {
        Ab04 update = MapstructUtils.convert(bo, Ab04.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Ab04 entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除原人员账户明细(缴费明细)信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 原人员账户明细(缴费明细)退费专用导出列表
     * @param ab04 账户明细(缴费明细)
     * @return 账户明细(缴费明细)
     */
    @Override
    public List<ExportAb04Vo> exportAb04(Ab04Bo ab04, String[] splitID) {
        return baseMapper.exportAb04(ab04,splitID);
    }

    /**
     * 批量修改已经退费的状态
     */
    @Override
    public Boolean updateAb04(String[] splitID) {
        return baseMapper.updateAb04(splitID)>0;
    }

    /**
     * 批量更新指定ID列表的字段
     * @param idList 主键ID列表
     * @return
     */
    @Override
    public int batchUpdateDelStatus(List<Long> idList) {
        return baseMapper.batchUpdateDelStatus(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<String> batchImport(List<Ab04ExcelDTO> excelList) {
        // 1. 数据转换（ExcelDTO -> 实体类Ab04）
        List<Ab04> ab04List = excelList.stream().map(dto -> {
            Ab04 ab04 = new Ab04();
            // 属性拷贝（可使用BeanUtils.copyProperties）
            ab04.setAaa027(dto.getAaa027());
            ab04.setDw01(dto.getDw01());
            ab04.setDw02(dto.getDw02());
            ab04.setGr03(dto.getGr03());
            ab04.setGr04(dto.getGr04());
            ab04.setGr02(dto.getGr02());
            ab04.setGrmx01(dto.getGrmx01());
            ab04.setGrmx02(dto.getGrmx02());
            ab04.setGrmx03(dto.getGrmx03());
            ab04.setGr18(dto.getGr18());
            ab04.setGr19(dto.getGr19());
            ab04.setGr20(dto.getGr20());
            ab04.setGrmx04(dto.getGrmx04());
            ab04.setGrmx05(dto.getGrmx05());
            ab04.setDw14(dto.getDw14());
            ab04.setCs03(dto.getCs03());
            ab04.setDw68(dto.getDw68());
            //ab04.setDw24(dto.getDw24());
            //ab04.setSystime(dto.getSystime());
            ab04.setGrjx01(dto.getGrjx01());
            //ab04.setTz01(dto.getTz01());
            //ab04.setDh(dto.getDh());
            //ab04.setDw91(dto.getDw91());
            //ab04.setStatus(dto.getStatus());
            //ab04.setDelStatus(dto.getDelStatus() != null ? dto.getDelStatus() : 0L); // 默认未删除
            //ab04.setDataFlag(dto.getDataFlag() != null ? dto.getDataFlag() : 0L); // 默认未计算
            //ab04.setRefStatus(dto.getRefStatus() != null ? dto.getRefStatus() : 0L); // 默认未退费
            //ab04.setFileurl(dto.getFileurl());
            ab04.setJfStarttime(dto.getJfStarttime());
            ab04.setJfEndtime(dto.getJfEndtime());
            ab04.setGr01(dto.getGr01());
            ab04.setJsStartmonth(dto.getJsStartmonth());
            ab04.setJsEndmonth(dto.getJsEndmonth());
            ab04.setJfPaymentmonths(dto.getJfPaymentmonths());
            ab04.setGrjfbx(dto.getGrjfbx());
            ab04.setGrzhbx(dto.getGrzhbx());
            ab04.setJfssfbz(dto.getJfssfbz());
            //ab04.setAaz223(dto.getAaz223());
            return ab04;
        }).collect(Collectors.toList());

        // 2. 数据校验（使用JSR303校验）
        List<String> errorMsgList = new ArrayList<>();
        for (int i = 0; i < ab04List.size(); i++) {
            Ab04 ab04 = ab04List.get(i);
            // 校验AddGroup分组的必填字段（需在实体类Ab04中启用@NotBlank等注解并指定groups=AddGroup.class）
            Set<ConstraintViolation<Ab04>> violations = validator.validate(ab04, AddGroup.class);
            if (!violations.isEmpty()) {
                String errorMsg = violations.stream()
                    .map(v -> v.getMessage())
                    .collect(Collectors.joining("；"));
                errorMsgList.add("第" + (i + 2) + "行数据错误：" + errorMsg); // Excel行号从2开始（表头为1行）
            }
        }

        // 3. 校验失败返回错误信息
        if (!errorMsgList.isEmpty()) {
            return R.fail("导入失败，错误信息：\n" + String.join("\n", errorMsgList));
        }

        // 4. 批量插入数据库
        int successCount = baseMapper.batchInsert(ab04List);
        return R.ok("导入成功，共导入" + successCount + "条数据");
    }

    @Override
    public void calculateSocialCost() {
        QueryWrapper<Ab02> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_status",0);
        //queryWrapper.isNotNull("zr_startmonth");
        List<Ab02> ab02List = ab02Mapper.selectList(queryWrapper);
        log.info("总人数：{}", ab02List.size());
            for (int i = 0; i < ab02List.size(); i++) {
                String gr03 = ab02List.get( i).getGr03();
                for (int j = 0; j < jrYear.length; j++){
                    QueryWrapper<Ab04Refund> queryWrapperRefund = new QueryWrapper<>();
                    queryWrapperRefund.eq("user_card",gr03);
                    queryWrapperRefund.eq("payment_time",jrYear[j]);
                    Long count =  ab04RefundMapper.selectCount(queryWrapperRefund);
                    if(count<=0){
                        Ab04Refund ab04Refund = new Ab04Refund();
                        ab04Refund.setPaymentTime(jrYear[j]);
                        ab04Refund.setUserCard(gr03);
                        ab04Refund.setCreateTime(new Date());
                        ab04Refund.setPersonnelStatus(2);
                        ab04Refund.setAccountingRate(BigDecimal.valueOf(Double.parseDouble(jrMonthRate[j])));
                        //计算每个人年份的缴费总数
                        Map<String,Object> mapYearCount = baseMapper.getUserYearCountAmount(Integer.parseInt(jrYear[j]),gr03);
                        //String zr_startmonth = ab02List.get(i).getZrStartmonth();
                        //String zr_endmonth = ab02List.get(i).getZrEndmonth();
                        //Map<String,Object> mapYearCount = baseMapper.getUserYearCountAmountInfo(zr_startmonth,zr_endmonth,gr02);
                        if(mapYearCount!=null){
                            BigDecimal gr20Count = (BigDecimal)mapYearCount.get("gr20Count");
                            BigDecimal divisor = new BigDecimal("12");
                            ab04Refund.setMonthlyPayment(gr20Count.divide(divisor, 2, RoundingMode.HALF_UP));
                            log.info("用户："+gr03+",缴费期间:"+ jrYear[j]+", 当年缴费总数："+gr20Count+", 当年记账利率:"+jrMonthRate[j]);
                            ab04Refund.setAnnualPayment(gr20Count);
                        }else{
                            log.info("用户："+gr03+"缴费期间:"+ jrYear[j]+", 当年缴费总数："+0+", 当年记账利率:"+jrMonthRate[j]);
                            ab04Refund.setAnnualPayment(BigDecimal.ZERO);
                            ab04Refund.setMonthlyPayment(BigDecimal.ZERO);
                        }
                        //计算添加每个人从1998-2014的缴费记录
                        ab04RefundMapper.insert(ab04Refund);
                    }else{
                        log.info("用户："+gr03+"已存在");
                    }
            }
        }
        calculateSocialCostInterestIncome();
    }

    @Override
    public void calculateSocialCostInterestIncome() {
        QueryWrapper<Ab02> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_status",0);
        List<Ab02> ab02List = ab02Mapper.selectList(queryWrapper);
        log.info("总人数：{}", ab02List.size());
            for (int i = 0; i < ab02List.size(); i++) {
                String  gr03 = ab02List.get( i).getGr03();
                QueryWrapper<Ab04Refund> queryWrapperAb04Refund = new QueryWrapper<>();
                queryWrapperAb04Refund.eq("user_card",gr03);
                List<Ab04Refund>  ab04RefundList = ab04RefundMapper.selectList(queryWrapperAb04Refund);
                for (int j = 0; j < ab04RefundList.size(); j++){
                    Ab04Refund ab04Refund = ab04RefundList.get(j);
                    if(ab04Refund!=null){
                        if(ab04Refund.getPaymentTime().equals("1998")){
                            ab04Refund.setLastYearAmount(BigDecimal.ZERO);
                            ab04Refund.setLastYearAccumulateAmount(BigDecimal.ZERO);
                            //本年缴纳的个人部分利息收入（月缴费额*（月缴费额/12）*78）
                            BigDecimal b = ab04Refund.getAccountingRate().divide(new BigDecimal("12"),6,RoundingMode.HALF_UP);
                            if(ab04Refund.getMonthlyPayment().compareTo(BigDecimal.ZERO)!=0){
                                BigDecimal  bb = ab04Refund.getMonthlyPayment();
                                BigDecimal currentYearInterestIncome = bb.multiply(b).multiply(new BigDecimal("78"));
                                ab04Refund.setCurrentYearInterestIncome(currentYearInterestIncome);
                            }else{
                                ab04Refund.setCurrentYearInterestIncome(BigDecimal.ZERO);
                            }
                            //利息收入小计(上年末个人账户累积额利息收入+本年缴纳的个人部分利息收入)
                            BigDecimal interestIncome = ab04Refund.getLastYearAccumulateAmount().add(ab04Refund.getCurrentYearInterestIncome());
                            ab04Refund.setInterestIncome(interestIncome);
                            ab04RefundMapper.updateById(ab04Refund);
                        }else{
                            Ab04Refund ab04RefundInfo = ab04RefundList.get(j-1);
                            //上年末个人账户累积额(上年末个人账户累积额+年个人缴费额（由月个人缴费明细组成）)
                            BigDecimal  lastYear = BigDecimal.ZERO;
                            if(ab04Refund.getLastYearAmount()!=null){
//                                log.info("上年末个人账户累积额 === "+ab04RefundInfo.getLastYearAmount()+" , 年个人缴费额 ==== "+ab04RefundInfo.getAnnualPayment());
                                lastYear = ab04RefundInfo.getLastYearAmount().add(ab04RefundInfo.getAnnualPayment());
                                log.info("年份："+ab04Refund.getPaymentTime()+" ， 上年末个人账户累积额 === "+lastYear);
                            }
                            ab04Refund.setLastYearAmount(lastYear);
                            //上年末个人账户累积额利息收入(上年末个人账户累积额*当年记账利率)
                            BigDecimal lastYearInterestIncome = lastYear.multiply(ab04Refund.getAccountingRate()).setScale(2, RoundingMode.HALF_UP);;
                            ab04Refund.setLastYearAccumulateAmount(lastYearInterestIncome);
                            //本年缴纳的个人部分利息收入（月缴费额*（月缴费额/12）*78）
                            BigDecimal b = ab04Refund.getAccountingRate().divide(new BigDecimal("12"),9,RoundingMode.HALF_UP);
                            if(ab04Refund.getMonthlyPayment().compareTo(BigDecimal.ZERO)!=0){
                                BigDecimal  bb = ab04Refund.getMonthlyPayment();
                                BigDecimal currentYearInterestIncome = bb.multiply(b).multiply(new BigDecimal("78"));
                                log.info(" 月缴费额 === currentYearInterestIncome"+currentYearInterestIncome);
                                ab04Refund.setCurrentYearInterestIncome(currentYearInterestIncome.setScale(5, RoundingMode.HALF_UP));
                            }else{
                                ab04Refund.setCurrentYearInterestIncome(BigDecimal.ZERO);
                            }
                            //利息收入小计(上年末个人账户累积额利息收入+本年缴纳的个人部分利息收入)
                            BigDecimal interestIncome = ab04Refund.getLastYearAccumulateAmount().add(ab04Refund.getCurrentYearInterestIncome());
//                            log.info(" 利息收入小计 === interestIncome"+interestIncome.setScale(5, RoundingMode.HALF_UP));
                            ab04Refund.setInterestIncome(interestIncome.setScale(5, RoundingMode.HALF_UP));
                            log.info("年份："+ab04Refund.getPaymentTime()+"，用户:"+gr03+" , 月缴费额 : "+ab04RefundInfo.getLastYearAmount()+" , 年个人缴费额："+ab04RefundInfo.getAnnualPayment());
                            ab04RefundMapper.updateById(ab04Refund);
                        }
                    }
                }
            }
    }

    @Override
    public void calculateSocialCostGr03(String gr03) {
        int del = baseMapper.delAb04Refund(gr03);
        if(del>0){
            log.info("已清除个人账号为:"+gr03+"的数据");
        }
        QueryWrapper<Ab02> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_status",0);
        queryWrapper.eq("gr03",gr03);
        List<Ab02> ab02List = ab02Mapper.selectList(queryWrapper);
        log.info("总人数：{}", ab02List.size());
        //计算缴费金额
        for (int i = 0; i < ab02List.size(); i++) {
            for (int j = 0; j < jrYear.length; j++){
                QueryWrapper<Ab04Refund> queryWrapperRefund = new QueryWrapper<>();
                queryWrapperRefund.eq("user_card",gr03);
                queryWrapperRefund.eq("payment_time",jrYear[j]);
                Long count =  ab04RefundMapper.selectCount(queryWrapperRefund);
                if(count<=0){
                    Ab04Refund ab04Refund = new Ab04Refund();
                    ab04Refund.setPaymentTime(jrYear[j]);
                    ab04Refund.setUserCard(gr03);
                    ab04Refund.setCreateTime(new Date());
                    ab04Refund.setPersonnelStatus(2);
                    ab04Refund.setAccountingRate(BigDecimal.valueOf(Double.parseDouble(jrMonthRate[j])));
                    //计算每个人年份的缴费总数
                    Map<String,Object> mapYearCount = baseMapper.getUserYearCountAmount(Integer.parseInt(jrYear[j]),gr03);
                    if(mapYearCount!=null){
                        BigDecimal gr20Count = (BigDecimal)mapYearCount.get("gr20Count");
                        BigDecimal divisor = new BigDecimal("12");
                        ab04Refund.setMonthlyPayment(gr20Count.divide(divisor, 2, RoundingMode.HALF_UP));
                        log.info("用户："+gr03+",缴费期间:"+ jrYear[j]+", 当年缴费总数："+gr20Count+", 当年记账利率:"+jrMonthRate[j]);
                        ab04Refund.setAnnualPayment(gr20Count);
                    }else{
                        log.info("用户："+gr03+"缴费期间:"+ jrYear[j]+", 当年缴费总数："+0+", 当年记账利率:"+jrMonthRate[j]);
                        ab04Refund.setAnnualPayment(BigDecimal.ZERO);
                        ab04Refund.setMonthlyPayment(BigDecimal.ZERO);
                    }
                    //计算添加每个人从1998-2014的缴费记录
                    ab04RefundMapper.insert(ab04Refund);
                }else{
                    log.info("用户："+gr03  +"已存在");
                }
            }
        }
        //计算利息收入
        QueryWrapper<Ab04Refund> queryWrapperAb04Refund = new QueryWrapper<>();
        queryWrapperAb04Refund.eq("user_card",gr03);
        List<Ab04Refund>  ab04RefundList = ab04RefundMapper.selectList(queryWrapperAb04Refund);
        for (int x = 0; x < ab04RefundList.size(); x++){
                Ab04Refund ab04Refund = ab04RefundList.get(x);
                if(ab04Refund!=null){
                    if(ab04Refund.getPaymentTime().equals("1998")){
                        ab04Refund.setLastYearAmount(BigDecimal.ZERO);
                        ab04Refund.setLastYearAccumulateAmount(BigDecimal.ZERO);
                        //本年缴纳的个人部分利息收入（月缴费额*（月缴费额/12）*78）
                        BigDecimal b = ab04Refund.getAccountingRate().divide(new BigDecimal("12"),6,RoundingMode.HALF_UP);
                        if(ab04Refund.getMonthlyPayment().compareTo(BigDecimal.ZERO)!=0){
                            BigDecimal  bb = ab04Refund.getMonthlyPayment();
                            BigDecimal currentYearInterestIncome = bb.multiply(b).multiply(new BigDecimal("78"));
                            ab04Refund.setCurrentYearInterestIncome(currentYearInterestIncome);
                        }else{
                            ab04Refund.setCurrentYearInterestIncome(BigDecimal.ZERO);
                        }
                        //利息收入小计(上年末个人账户累积额利息收入+本年缴纳的个人部分利息收入)
                        BigDecimal interestIncome = ab04Refund.getLastYearAccumulateAmount().add(ab04Refund.getCurrentYearInterestIncome());
                        ab04Refund.setInterestIncome(interestIncome);
                        ab04RefundMapper.updateById(ab04Refund);
                    }else{
                        Ab04Refund ab04RefundInfo = ab04RefundList.get(x-1);
                        //上年末个人账户累积额(上年末个人账户累积额+年个人缴费额（由月个人缴费明细组成）)
                        BigDecimal  lastYear = BigDecimal.ZERO;
                        if(ab04Refund.getLastYearAmount()!=null){
//                                log.info("上年末个人账户累积额 === "+ab04RefundInfo.getLastYearAmount()+" , 年个人缴费额 ==== "+ab04RefundInfo.getAnnualPayment());
                            lastYear = ab04RefundInfo.getLastYearAmount().add(ab04RefundInfo.getAnnualPayment());
                            log.info("年份："+ab04Refund.getPaymentTime()+" ， 上年末个人账户累积额 === "+lastYear);
                        }
                        ab04Refund.setLastYearAmount(lastYear);
                        //上年末个人账户累积额利息收入(上年末个人账户累积额*当年记账利率)
                        BigDecimal lastYearInterestIncome = lastYear.multiply(ab04Refund.getAccountingRate()).setScale(2, RoundingMode.HALF_UP);;
                        ab04Refund.setLastYearAccumulateAmount(lastYearInterestIncome);
                        //本年缴纳的个人部分利息收入（月缴费额*（月缴费额/12）*78）
                        BigDecimal b = ab04Refund.getAccountingRate().divide(new BigDecimal("12"),9,RoundingMode.HALF_UP);
                        if(ab04Refund.getMonthlyPayment().compareTo(BigDecimal.ZERO)!=0){
                            BigDecimal  bb = ab04Refund.getMonthlyPayment();
                            BigDecimal currentYearInterestIncome = bb.multiply(b).multiply(new BigDecimal("78"));
                            log.info(" 月缴费额 === currentYearInterestIncome"+currentYearInterestIncome);
                            ab04Refund.setCurrentYearInterestIncome(currentYearInterestIncome.setScale(5, RoundingMode.HALF_UP));
                        }else{
                            ab04Refund.setCurrentYearInterestIncome(BigDecimal.ZERO);
                        }
                        //利息收入小计(上年末个人账户累积额利息收入+本年缴纳的个人部分利息收入)
                        BigDecimal interestIncome = ab04Refund.getLastYearAccumulateAmount().add(ab04Refund.getCurrentYearInterestIncome());
//                            log.info(" 利息收入小计 === interestIncome"+interestIncome.setScale(5, RoundingMode.HALF_UP));
                        ab04Refund.setInterestIncome(interestIncome.setScale(5, RoundingMode.HALF_UP));
                        log.info("年份："+ab04Refund.getPaymentTime()+"，用户:"+gr03+" , 月缴费额 : "+ab04RefundInfo.getLastYearAmount()+" , 年个人缴费额："+ab04RefundInfo.getAnnualPayment());
                        ab04RefundMapper.updateById(ab04Refund);
                    }
                }
            }
    }
}
